package cn.tedu.sp11.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.tedu.web.util.JsonResult;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class AccessFilter extends ZuulFilter {
    //过滤器类型：pre(前置)，routing（路由），post（后置）,error

    @Override
    public String filterType() {
        //return pre;
        return FilterConstants.PRE_TYPE;
    }

    //过滤器插入的位置
    @Override
    public int filterOrder() {
        return 6;
    }

    //对用户请求进行判断，是否执行过滤代码
    @Override
    public boolean shouldFilter() {
      /*
        只对 item-service 调用进行过滤
        如果调用 user-service 或 order-service，不执行过滤代码
      */
        //获得调用的服务ID
        RequestContext ctx = RequestContext.getCurrentContext();
        String serviceId =(String) ctx.get(FilterConstants.SERVICE_ID_KEY);
        return "item-service".equalsIgnoreCase(serviceId);
    }

    //过滤代码
    @Override
    public Object run() throws ZuulException {
         /*
        http://localhost:3001/item-service/y45y45y4y   没有登录，不允许访问
        http://localhost:3001/item-service/y45y45y4y?token=3t3t34t   已登录
         */

        //获取request对象
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();

        //接受token参数
        String token = request.getParameter("token");

        //如果没有token，阻止访问，并直接向客户端返回响应
        if (StringUtils.isBlank(token)){
            //阻止继续访问
            ctx.setSendZuulResponse(false);
         // JsonResult {code:400, msg:not login, data:null}
            String json= JsonResult.err()
                    .code(JsonResult.NOT_LOGIN)
                    .msg("not login")
                    .toString();
            ctx.addZuulResponseHeader("Content-Type", "application/json;charset=UTF-8");
            ctx.setResponseBody(json);
        }
            return null;//返回值没有任何作用
    }
}
